<template>
  <div class="news-management">
    <!-- 搜索条件 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="新闻标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入新闻标题"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="新闻分类" prop="category">
          <el-select v-model="queryParams.category" placeholder="请选择新闻分类" clearable style="width: 200px">
            <el-option label="系统公告" value="announcement" />
            <el-option label="政策解读" value="policy" />
            <el-option label="行业动态" value="industry" />
            <el-option label="使用指南" value="guide" />
            <el-option label="活动推广" value="activity" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="publishStatus">
          <el-select v-model="queryParams.publishStatus" placeholder="请选择发布状态" clearable style="width: 200px">
            <el-option label="已发布" value="1" />
            <el-option label="未发布" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶状态" prop="isTop">
          <el-select v-model="queryParams.isTop" placeholder="请选择置顶状态" clearable style="width: 200px">
            <el-option label="置顶" value="1" />
            <el-option label="不置顶" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="table-card" shadow="never">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-upload"
            size="mini"
            :disabled="multiple"
            @click="handleBatchPublish"
          >批量发布</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 新闻列表表格 -->
      <el-table
        v-loading="loading"
        :data="newsList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="新闻ID" prop="newsId" width="80" />
        <el-table-column label="新闻标题" prop="title" width="250" show-overflow-tooltip />
        <el-table-column label="新闻分类" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getCategoryTag(scope.row.category)" size="small">
              {{ getCategoryName(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="作者" prop="author" width="100" />
        <el-table-column label="阅读量" prop="readCount" width="100" align="center" sortable="custom">
          <template slot-scope="scope">
            <span class="read-count">{{ scope.row.readCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.publishStatus"
              :active-value="1"
              :inactive-value="0"
              @change="handlePublishChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="置顶" width="80" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              :class="scope.row.isTop === 1 ? 'text-warning' : 'text-info'"
              @click="handleTopChange(scope.row)"
            >
              <i :class="scope.row.isTop === 1 ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
            >预览</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改新闻对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入新闻标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新闻分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择新闻分类" style="width: 100%">
                <el-option label="系统公告" value="announcement" />
                <el-option label="政策解读" value="policy" />
                <el-option label="行业动态" value="industry" />
                <el-option label="使用指南" value="guide" />
                <el-option label="活动推广" value="activity" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布状态" prop="publishStatus">
              <el-radio-group v-model="form.publishStatus">
                <el-radio :label="1">立即发布</el-radio>
                <el-radio :label="0">保存草稿</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="新闻摘要" prop="summary">
          <el-input
            v-model="form.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入新闻摘要，建议100-200字"
          />
        </el-form-item>
        <el-form-item label="新闻内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="8"
            placeholder="请输入新闻详细内容"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否置顶" prop="isTop">
              <el-switch
                v-model="form.isTop"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number
                v-model="form.sortOrder"
                :min="0"
                :max="999"
                placeholder="数值越大越靠前"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新闻预览对话框 -->
    <el-dialog title="新闻预览" :visible.sync="previewDialogVisible" width="800px" append-to-body>
      <div class="news-preview">
        <div class="news-header">
          <h2>{{ currentNews.title }}</h2>
          <div class="news-meta">
            <span class="author">作者：{{ currentNews.author }}</span>
            <span class="time">发布时间：{{ parseTime(currentNews.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            <span class="category">
              <el-tag :type="getCategoryTag(currentNews.category)" size="small">
                {{ getCategoryName(currentNews.category) }}
              </el-tag>
            </span>
            <span class="read-count">阅读量：{{ currentNews.readCount || 0 }}</span>
          </div>
        </div>
        <div class="news-summary">
          <p><strong>摘要：</strong>{{ currentNews.summary }}</p>
        </div>
        <div class="news-content">
          <div v-html="formatContent(currentNews.content)"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getNewsList, getNews, addNews, updateNews, delNews, batchPublishNews, setNewsTop, exportNews, getNewsStatistics } from '@/api/credit/admin'

export default {
  name: 'CreditNewsManagement',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻表格数据
      newsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        category: null,
        publishStatus: null,
        isTop: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '新闻标题不能为空', trigger: 'blur' },
          { min: 5, max: 100, message: '新闻标题长度在5到100个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '新闻分类不能为空', trigger: 'change' }
        ],
        author: [
          { required: true, message: '作者不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '作者姓名长度在2到20个字符', trigger: 'blur' }
        ],
        summary: [
          { required: true, message: '新闻摘要不能为空', trigger: 'blur' },
          { min: 20, max: 300, message: '新闻摘要长度在20到300个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '新闻内容不能为空', trigger: 'blur' },
          { min: 50, message: '新闻内容至少50个字符', trigger: 'blur' }
        ]
      },
      
      // 新闻预览对话框
      previewDialogVisible: false,
      currentNews: {}
    }
  },
  
  created() {
    this.getList()
  },
  
  methods: {
    /** 查询新闻列表 */
    getList() {
      this.loading = true
      getNewsList(this.queryParams).then(response => {
        this.newsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    
    /** 表单重置 */
    reset() {
      this.form = {
        newsId: null,
        title: null,
        category: null,
        author: null,
        summary: null,
        content: null,
        publishStatus: 0,
        isTop: 0,
        sortOrder: 0,
        remark: null
      }
      this.resetForm('form')
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.newsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    
    /** 排序变化处理 */
    handleSortChange(sort) {
      if (sort.prop === 'readCount') {
        this.queryParams.orderByColumn = 'read_count'
        this.queryParams.isAsc = sort.order === 'ascending' ? 'asc' : 'desc'
        this.getList()
      }
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加新闻'
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const newsId = row.newsId || this.ids
      getNews(newsId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改新闻'
      })
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.newsId != null) {
            updateNews(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addNews(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const newsIds = row.newsId || this.ids
      this.$modal.confirm('是否确认删除新闻编号为"' + newsIds + '"的数据项？').then(function() {
        return delNews(newsIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    
    /** 发布状态修改 */
    handlePublishChange(row) {
      let text = row.publishStatus === 1 ? '发布' : '取消发布'
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"新闻吗？').then(function() {
        return updateNews({
          newsId: row.newsId,
          publishStatus: row.publishStatus
        })
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.publishStatus = row.publishStatus === 0 ? 1 : 0
      })
    },
    
    /** 置顶状态修改 */
    handleTopChange(row) {
      let text = row.isTop === 1 ? '取消置顶' : '置顶'
      let newStatus = row.isTop === 1 ? 0 : 1
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"新闻吗？').then(function() {
        return setNewsTop({
          newsId: row.newsId,
          isTop: newStatus
        })
      }).then(() => {
        row.isTop = newStatus
        this.$modal.msgSuccess(text + '成功')
      }).catch(() => {})
    },
    
    /** 批量发布 */
    handleBatchPublish() {
      if (this.ids.length === 0) {
        this.$modal.msgError('请先选择要发布的新闻')
        return
      }
      this.$modal.confirm('确认要批量发布选中的新闻吗？').then(() => {
        return batchPublishNews({
          newsIds: this.ids,
          publishStatus: 1
        })
      }).then(() => {
        this.$modal.msgSuccess('批量发布成功')
        this.getList()
      }).catch(() => {})
    },
    
    /** 预览新闻 */
    handlePreview(row) {
      this.currentNews = { ...row }
      this.previewDialogVisible = true
    },
    
    /** 获取分类标签 */
    getCategoryTag(category) {
      const tagMap = {
        'announcement': 'danger',
        'policy': 'warning',
        'industry': 'success',
        'guide': 'primary',
        'activity': 'info'
      }
      return tagMap[category] || 'info'
    },
    
    /** 获取分类名称 */
    getCategoryName(category) {
      const nameMap = {
        'announcement': '系统公告',
        'policy': '政策解读',
        'industry': '行业动态',
        'guide': '使用指南',
        'activity': '活动推广'
      }
      return nameMap[category] || '未知'
    },
    
    /** 格式化内容 */
    formatContent(content) {
      if (!content) return ''
      // 简单的换行处理
      return content.replace(/\n/g, '<br/>')
    }
  }
}
</script>

<style lang="scss" scoped>
.news-management {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .mb8 {
      margin-bottom: 8px;
    }
  }
  
  .read-count {
    color: #409EFF;
    font-weight: bold;
  }
  
  .text-warning {
    color: #E6A23C;
  }
  
  .text-info {
    color: #909399;
  }
  
  .news-preview {
    .news-header {
      margin-bottom: 20px;
      
      h2 {
        margin: 0 0 10px 0;
        color: #303133;
        font-size: 24px;
        line-height: 1.4;
      }
      
      .news-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        color: #909399;
        font-size: 14px;
        
        .author, .time, .read-count {
          color: #606266;
        }
      }
    }
    
    .news-summary {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #f8f9fa;
      border-left: 4px solid #409EFF;
      
      p {
        margin: 0;
        line-height: 1.6;
        color: #606266;
      }
    }
    
    .news-content {
      line-height: 1.8;
      color: #303133;
      
      ::v-deep p {
        margin-bottom: 15px;
      }
    }
  }
}
</style> 